<template>
  <div class="clause-create-container">
    <div class="header">
      <h2>创建新条款</h2>
      <div class="breadcrumb">
        <router-link to="/contracts">合同管理</router-link> >
        <span v-if="fromContractEdit">合同编辑</span>
        <router-link v-else :to="`/contracts/${contractId}`">合同详情</router-link> >
        创建新条款
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 成功消息 -->
    <div v-if="successMessage" class="success-message">
      <i class="fa fa-check-circle mr-2"></i>{{ successMessage }}
    </div>

    <!-- AI助手对话模态框 -->
    <transition name="modal-fade">
      <div v-if="aiAssistantVisible" class="modal-backdrop" @click.self="closeAIAssistant">
        <div class="modal-dialog ai-modal" role="document">
          <div class="modal-content ai-content">
            <div class="modal-header ai-header">
              <h3 class="modal-title">条款助手</h3>
              <button type="button" class="close" @click="closeAIAssistant">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body ai-body">
              <!-- 对话消息区域 -->
              <div class="chat-messages" ref="chatContainer">
                <div v-for="(msg, index) in chatHistory" :key="index" class="message" :class="msg.type">
                  <div class="avatar" :class="msg.type">{{ msg.type === 'user' ? '👤' : '🤖' }}</div>
                  <div class="message-content">
                    <!-- AI思考过程（仅AI消息显示） -->
                    <div v-if="msg.type === 'assistant' && msg.thinking" class="thinking-process">
                      <span class="thinking-label">思考过程：</span>
                      <p>{{ msg.thinking }}</p>
                    </div>
                    <!-- 核心回答内容 -->
                    <div class="answer-content">
                      <p>{{ msg.answer || msg.content }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 输入区域 -->
              <div class="chat-input">
                <textarea
                    v-model="aiQuery"
                    placeholder="请输入您的问题，例如：'帮我生成一个违约责任条款'"
                    @keyup.enter="sendAIQuery"
                ></textarea>
                <button @click="sendAIQuery" class="send-btn" :disabled="aiLoading">
                  <i class="fa fa-paper-plane"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 条款创建表单 -->
    <div v-if="!loading && !submitted" class="card">
      <div class="card-body">
        <form @submit.prevent="createClause">
          <div class="form-group">
            <label for="clauseContent">条款内容:</label>
            <textarea
                id="clauseContent"
                v-model="clauseContent"
                rows="10"
                class="form-control"
                placeholder="请输入条款内容，例如：'甲方应在合同签订后10个工作日内支付预付款'"
                required
            ></textarea>
          </div>

          <div class="button-group mt-4 d-flex justify-content-end gap-2">
            <button
                @click="goBack"
                class="btn btn-secondary"
            >
              <i class="fa fa-arrow-left mr-2"></i>返回
            </button>
            <button
                v-if="!fromContractEdit"
                @click="goToContractEdit"
                class="btn btn-info"
            >
              <i class="fa fa-edit mr-2"></i>返回编辑界面
            </button>
            <button
                @click="openAIAssistant"
                class="btn btn-primary"
            >
              <i class="fa fa-robot mr-2"></i>AI助手
            </button>
            <button
                type="submit"
                class="btn btn-success"
                :disabled="isSubmitting"
            >
              <i class="fa fa-save mr-2"></i>保存条款
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 提交成功后显示 -->
    <div v-if="submitted" class="success-card">
      <div class="success-icon">
        <i class="fa fa-check-circle"></i>
      </div>
      <h3>条款创建成功</h3>
      <p>您的条款已成功添加到合同中。</p>
      <div class="button-group d-flex justify-content-center gap-3 mt-4">
        <button
            @click="goToContractEdit"
            class="btn btn-primary"
        >
          <i class="fa fa-edit mr-2"></i>返回编辑界面
        </button>
        <button
            @click="goToContractDetail"
            class="btn btn-info"
        >
          <i class="fa fa-eye mr-2"></i>查看合同详情
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ClauseCreate',
  data() {
    return {
      contractId: null,
      clauseContent: '',
      errorMessage: '',
      successMessage: '',
      loading: false,
      isSubmitting: false,
      submitted: false,
      fromContractEdit: false,
      aiAssistantVisible: false,
      aiQuery: '',
      chatHistory: [],
      aiLoading: false
    }
  },
  created() {
    this.contractId = this.$route.params.contractId
    console.log('ClauseCreate组件初始化，合同ID:', this.contractId)

    if (!this.contractId) {
      this.errorMessage = '缺少合同ID参数'
      setTimeout(() => {
        this.$router.push('/contracts')
      }, 2000)
    } else {
      const fromPath = this.$route.meta.from?.path || ''
      this.fromContractEdit = fromPath.includes('/contracts/\\d+/edit')
      console.log('来源页面:', this.fromContractEdit ? '合同编辑' : '合同详情')
    }
  },
  methods: {
    // 解析AI返回的内容（格式："<think>思考过程</think>回答内容"）
    parseAIResponse(responseText) {
      // 定义开始和结束标签
      const startTag = '<think>'
      const endTag = '</think>'

      // 查找标签位置
      const startIndex = responseText.indexOf(startTag)
      const endIndex = responseText.indexOf(endTag)

      // 如果格式不正确，返回完整内容作为回答
      if (startIndex === -1 || endIndex === -1 || startIndex >= endIndex) {
        return {
          thinking: '（未获取到思考过程）',
          answer: responseText.trim() || '（无有效回答内容）'
        }
      }

      // 提取思考过程和回答
      const thinking = responseText.substring(startIndex + startTag.length, endIndex).trim()
      const answer = responseText.substring(endIndex + endTag.length).trim()

      return {
        thinking: thinking || '（无思考过程）',
        answer: answer || '（无有效回答内容）'
      }
    },

    // 打开AI助手对话框
    openAIAssistant() {
      this.aiAssistantVisible = true
      // 初始化对话历史
      this.chatHistory = [
        { type: 'assistant', content: '你好！我是条款助手，需要帮你生成或优化条款吗？' }
      ]
    },

    // 关闭AI助手对话框
    closeAIAssistant() {
      this.aiAssistantVisible = false
      this.aiQuery = ''
    },

    // 发送AI查询
    sendAIQuery() {
      const query = this.aiQuery.trim()
      if (!query) return

      // 添加用户消息到对话历史
      this.chatHistory.push({ type: 'user', content: query })
      this.aiQuery = ''
      this.aiLoading = true

      // 添加"思考中"提示
      this.chatHistory.push({ type: 'assistant', content: '正在生成回答，请稍候...' })
      this.scrollToBottom()

      // 调用后端API获取AI回答
      axios.post('/auth/ai/query', {
        query,
        contractId: this.contractId
      })
          .then(response => {
            // 移除"思考中"提示
            this.chatHistory.pop()

            // 解析AI返回结果
            const aiResponse = this.parseAIResponse(response.data.answer || '')

            // 添加AI回答到对话历史
            this.chatHistory.push({
              type: 'assistant',
              thinking: aiResponse.thinking,
              answer: aiResponse.answer
            })

            // 自动填充条款文本框（仅填入回答部分）
            this.clauseContent = aiResponse.answer
          })
          .catch(error => {
            // 移除"思考中"提示
            this.chatHistory.pop()

            console.error('AI查询失败:', error)
            this.chatHistory.push({
              type: 'assistant',
              content: '抱歉，生成回答失败，请稍后重试（错误：' + (error.message || '未知错误') + '）'
            })
          })
          .finally(() => {
            this.aiLoading = false
            this.scrollToBottom()
          })
    },

    // 滚动到对话底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    },

    createClause() {
      if (!this.clauseContent.trim()) {
        this.errorMessage = '条款内容不能为空'
        return
      }

      this.isSubmitting = true
      this.errorMessage = ''

      console.log('开始创建新条款', this.clauseContent)

      axios.post('/auth/clauses/create', { content: this.clauseContent })
          .then(response => {
            const clauseId = response.data.id
            console.log('新条款创建成功，ID:', clauseId)

            // 关联条款到合同
            return axios.post('/auth/clauses/associate', {
              contractId: this.contractId,
              clauseId: clauseId,
              type: 'INITIAL'
            })
          })
          .then(() => {
            console.log('条款关联成功')
            this.submitted = true
            this.successMessage = '新条款创建成功'
          })
          .catch((err) => {
            console.error('创建新条款失败', err)
            if (err.response && err.response.data && err.response.data.message) {
              this.errorMessage = err.response.data.message
            } else if (err.response && err.response.status === 500) {
              this.errorMessage = '服务器内部错误，请联系管理员'
            } else {
              this.errorMessage = '创建条款失败，请重试'
            }
            this.isSubmitting = false
          })
    },

    goBack() {
      if (this.fromContractEdit) {
        this.$router.push(`/contracts/${this.contractId}/edit`)
      } else {
        this.$router.push(`/contracts/${this.contractId}`)
      }
    },

    goToContractEdit() {
      this.$router.push(`/contracts/${this.contractId}/edit`)
    },

    goToContractDetail() {
      this.$router.push(`/contracts/${this.contractId}`)
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变，增加以下内容 */

/* 思考过程样式 */
.thinking-process {
  font-size: 0.9em;
  color: #6c757d;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  border-left: 3px solid #007bff;
}

.thinking-label {
  font-weight: 600;
  margin-right: 5px;
  color: #007bff;
}

/* 回答内容样式 */
.answer-content {
  line-height: 1.6;
}
</style>

<style scoped>
.clause-create-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.breadcrumb {
  font-size: 0.9rem;
  color: #6c757d;
  margin-top: 10px;
}

.breadcrumb router-link {
  color: #007bff;
  text-decoration: none;
}

.breadcrumb router-link:hover {
  text-decoration: underline;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.success-message {
  color: #155724;
  background-color: #d4edda;
  border-left: 4px solid #c3e6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.card {
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.card-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #495057;
}

.form-control {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  cursor: pointer;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0069d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 123, 255, 0.2);
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #138496;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(23, 162, 184, 0.2);
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(40, 167, 69, 0.2);
}

.button-group {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: flex-end;
}

.success-card {
  text-align: center;
  padding: 40px 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background-color: #f8f9fa;
  margin-top: 40px;
}

.success-icon {
  font-size: 48px;
  color: #28a745;
  margin-bottom: 20px;
}

.success-card h3 {
  font-size: 24px;
  margin-bottom: 10px;
}

.success-card p {
  color: #6c757d;
  margin-bottom: 20px;
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  overflow-y: auto;
}

.modal-dialog {
  max-width: 600px;
  width: 90%;
  margin: 20px;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 1.2rem;
  font-weight: 500;
  color: #212529;
}

.close {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #6c757d;
  cursor: pointer;
  transition: color 0.3s;
}

.close:hover {
  color: #212529;
}

.modal-body {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
}

/* AI助手样式 */
.ai-modal {
  max-width: 700px;
}

.ai-header {
  background-color: #f8f9fa;
}

.ai-body {
  display: flex;
  flex-direction: column;
  height: 400px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  gap: 10px;
  max-width: 90%;
}

.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.assistant {
  align-self: flex-start;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  flex-shrink: 0;
}

.user .avatar {
  background-color: #007bff;
  color: white;
}

.assistant .avatar {
  background-color: #28a745;
  color: white;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
  max-width: calc(100% - 42px);
}

.user .message-content {
  background-color: #007bff;
  color: white;
}

.assistant .message-content {
  background-color: #f1f0f0;
  color: #212529;
}

/* 思考过程与回答样式区分 */
.thinking-process {
  font-size: 0.85rem;
  color: #6c757d;
  padding: 8px 0;
  border-left: 2px solid #dee2e6;
  padding-left: 10px;
  margin-bottom: 8px;
}

.thinking-label {
  font-weight: 600;
  font-size: 0.8rem;
  color: #495057;
  display: inline-block;
  margin-bottom: 4px;
}

.answer-content {
  font-size: 1rem;
  line-height: 1.5;
}

/* 用户消息不显示思考过程相关样式 */
.message.user .thinking-process {
  display: none;
}

.chat-input {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.chat-input textarea {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 16px;
  resize: none;
  transition: border-color 0.3s;
  min-height: 60px;
}

.chat-input textarea:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.send-btn {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
  align-self: flex-end;
}

.send-btn:hover {
  background-color: #0069d9;
}

.send-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

/* 动画效果 */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s;
}

.modal-fade-enter,
.modal-fade-leave-to {
  opacity: 0;
}
</style>